package com.hslxy.niukewang.controller;

import com.hslxy.niukewang.annotation.LoginRequired;
import com.hslxy.niukewang.component.Page;
import com.hslxy.niukewang.entity.Comment;
import com.hslxy.niukewang.entity.DiscussPost;
import com.hslxy.niukewang.entity.User;
import com.hslxy.niukewang.service.*;
import com.hslxy.niukewang.util.CommunityUtil;
import com.hslxy.niukewang.util.Constant;
import com.hslxy.niukewang.util.HostHolder;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController implements Constant {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Value("${niukewang.path.domain}")
    private String domainPath;

    @Value("${niukewang.path.upload}")
    private String uploadPath;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private UserService userService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private LikeService likeService;

    @Autowired
    private FollowService followService;

    @Autowired
    private DiscussPostService discussPostService;

    @Value("${qiniu.key.access}")
    private String accessKey;

    @Value("${qiniu.key.secret}")
    private String secretKey;

    @Value("${qinniu.bucket.header.name}")
    private String headerBucket;

    @Value("${qinniu.bucket.header.url}")
    private String headerBucketUrl;

    @LoginRequired
    @RequestMapping(path = "/setting", method = RequestMethod.GET)
    public String getSettingPage(Model model){
//        生成上传凭证
        String fileName = CommunityUtil.generateUUID();
        Auth auth = Auth.create(accessKey, secretKey);
        StringMap putPolicy = new StringMap();
        putPolicy.put("returnBody", CommunityUtil.getJSONString(0));
        long expireSeconds = 3600;
        fileName = "niukewang/header/" + fileName;
        String upToken = auth.uploadToken(headerBucket, fileName, expireSeconds, putPolicy);
        model.addAttribute("upToken", upToken);
        model.addAttribute("fileName", fileName);
        return "/site/setting";
    }

    @RequestMapping(path = "/header/url", method = RequestMethod.POST)
    @ResponseBody
    public String updateHeaderUrl(String fileName){
        if(StringUtils.isBlank(fileName)){
            return CommunityUtil.getJSONString(1, "文件名不能为空");
        }
        String url = headerBucketUrl + fileName;
        userService.updateHeader(hostHolder.getUsers().getId(), url);
        return CommunityUtil.getJSONString(0);
    }

    @LoginRequired
    @RequestMapping(path = "/upload", method = RequestMethod.POST)
    public String uploadHeaderImage(MultipartFile headerImage, Model model){
        if (headerImage == null){
            model.addAttribute("error", "您还没上传照片");
            return "/site/setting";
        }
        String fileName = headerImage.getOriginalFilename();
        String substring = fileName.substring(fileName.lastIndexOf("."));
        if(StringUtils.isBlank(substring)){
            model.addAttribute("error", "文件格式不对");
            return "/site/setting";
        }
        fileName = CommunityUtil.generateUUID() + substring;
        File dest = new File(uploadPath + "/" + fileName);
        try {
            headerImage.transferTo(dest);
        } catch (IOException e) {
            logger.error("上传文件失败", e);
            throw new RuntimeException(e);
        }
//        更新用户路径
        User user = hostHolder.getUsers();
        String headerUrl = domainPath + contextPath + "/user/header/" + fileName;
        userService.updateHeader(user.getId(), headerUrl);
        return "redirect:/index";
    }

    @RequestMapping(path = "/header/{filename}", method = RequestMethod.GET)
    public void getHeaderImage(@PathVariable("filename") String filename, HttpServletResponse response){
        filename = uploadPath + "/" + filename;
        String substring = filename.substring(filename.lastIndexOf("."));
        response.setContentType("image/" + substring);
        try(
                FileInputStream file = new FileInputStream(filename);
                OutputStream outputStream = response.getOutputStream();
        ) {
            byte[] buffer = new byte[1024];
            int b=0;
            while((b = file.read(buffer)) != -1){
                outputStream.write(buffer, 0, b);
            }
        } catch (IOException e) {
            logger.error("读取头像失败:" + e.getMessage());
            throw new RuntimeException(e);
        }
    }

    @LoginRequired
    @RequestMapping(path = "/update/password", method = RequestMethod.POST)
    public String uploadPassword(String oldPassword, String newPassword, Model model){
        Map<String, Object> map = userService.updatePassword(oldPassword, newPassword);
        if (map != null && !map.isEmpty()){
            model.addAttribute("oldPasswordMsg", map.get("oldPasswordMsg"));
            model.addAttribute("newPasswordMsg", map.get("newPasswordMsg"));
            return "/site/setting";
        }
        return "redirect:/logout";
    }

    @RequestMapping(path = "/profile/{userId}", method = RequestMethod.GET)
    public String getProfilePage(@PathVariable("userId") int userId, Model model){
        User userById = userService.findUserById(userId);
        if(userById == null){
            throw new RuntimeException("该用户不存在");
        }
        model.addAttribute("user", userById);
//        点赞数量
        int userLikeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("userLike", userLikeCount);
//        关注数量
        long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER);
        model.addAttribute("followeeCount", followeeCount);
//        被关注数量
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER, userId);
        model.addAttribute("followerCount", followerCount);
//        是否被关注
//        看我的关注列表里是否有我正在看的userId
        boolean followed = false;
        if(hostHolder.getUsers() != null){
            followed = followService.isFollowed(hostHolder.getUsers().getId(), ENTITY_TYPE_USER, userId);
        }
        model.addAttribute("followed", followed);

        return "/site/profile";
    }

    // 我的帖子
    @RequestMapping(path = "/mypost/{userId}", method = RequestMethod.GET)
    public String getMyPost(@PathVariable("userId") int userId, Page page, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在！");
        }
        model.addAttribute("user", user);

        // 分页信息
        page.setPath("/user/mypost/" + userId);
        page.setRows(discussPostService.findDiscussPostRows(userId));

        // 帖子列表
        List<DiscussPost> discussList = discussPostService
                .findDiscussPosts(userId, page.getOffset(), page.getLimit(), 0);
        List<Map<String, Object>> discussVOList = new ArrayList<>();
        if (discussList != null) {
            for (DiscussPost post : discussList) {
                Map<String, Object> map = new HashMap<>();
                map.put("discussPost", post);
                map.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId()));
                discussVOList.add(map);
            }
        }
        model.addAttribute("discussPosts", discussVOList);

        return "/site/my-post";
    }

    // 我的回复
    @RequestMapping(path = "/myreply/{userId}", method = RequestMethod.GET)
    public String getMyReply(@PathVariable("userId") int userId, Page page, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在！");
        }
        model.addAttribute("user", user);

        // 分页信息
        page.setPath("/user/myreply/" + userId);
        page.setRows(commentService.findUserCommentsCount(userId));

        // 回复列表
        List<Comment> commentList = commentService.findUserComments(userId, page.getOffset(), page.getLimit());
        List<Map<String, Object>> commentVOList = new ArrayList<>();
        if (commentList != null) {
            for (Comment comment : commentList) {
                Map<String, Object> map = new HashMap<>();
                map.put("comment", comment);
                DiscussPost post = discussPostService.findDiscussPost(comment.getEntityId());
                map.put("discussPost", post);
                commentVOList.add(map);
            }
        }
        model.addAttribute("comments", commentVOList);

        return "/site/my-reply";
    }

}
